﻿using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Super
{
	[ExecuteInEditMode]
	[RequireComponent(typeof(Image))]
	public class AsyncImage : MonoBehaviour
	{
		private Image imageConmponent;
		public Image ImageConmponent
		{
			get
			{
				if (imageConmponent == null)
					imageConmponent = GetComponent<Image>();
				return imageConmponent;
			}
		}

		[SerializeField]
		private Sprite imageSprite;
		private Sprite oldImageSprite;

		public string imageAName = "";
		private string oldImageAName;

		public void OnValidate()
		{
			bool isChangeSprite = imageSprite != oldImageSprite;
			bool isChangeAName = imageAName != oldImageAName;
			bool isClearSprite = imageSprite == null;
			bool isAssetExist = AssetUtil.AssetExist(imageAName);
			bool isClearAName = string.IsNullOrEmpty(imageAName);

#if UNITY_EDITOR
			if (isChangeSprite && !isClearSprite)
			{
				OnSetImageSprite();
			}
			else if (isChangeAName && !isClearAName && isAssetExist)
			{
				OnSetImageAName();
			}
			else if ((isChangeAName && isClearAName) || (isChangeSprite && isClearSprite))
			{
				OnClear();
			}
#endif
		}
		
		private void OnSetImageSprite()
		{
			oldImageSprite = imageSprite;
			ImageConmponent.sprite = imageSprite;
#if UNITY_EDITOR
			imageAName = AssetDatabase.GetAssetPath(imageSprite);
			oldImageAName = imageAName;
			if (!AssetUtil.AExist(imageAName))
			{
				AssetUtil.ACreateOrMove(DefaultConfig.spritAGroup, imageAName);
			}
#endif
		}
		private void OnSetImageAName()
		{
			oldImageAName = imageAName;
			Sprite sprite = AssetUtil.ALoadAsset<Sprite>(imageAName);
			imageSprite = sprite;
			oldImageSprite = imageSprite;
			ImageConmponent.sprite = imageSprite;
#if UNITY_EDITOR
			if (!AssetUtil.AExist(imageAName))
			{
				AssetUtil.ACreateOrMove(DefaultConfig.spritAGroup, imageAName);
			}
#endif
		}
		private void OnClear()
		{
			imageAName = "";
			oldImageAName = imageAName;
			imageSprite = null;
			oldImageSprite = imageSprite;
			ImageConmponent.sprite = imageSprite;
		}

		public void SetImageAName(string imageAName)
		{
			this.imageAName = imageAName;
			OnSetImageAName();
		}

		public void SetImageSprite(Sprite imageSprite)
		{
			this.imageSprite = imageSprite;
			OnSetImageSprite();
		}
	}
}

